//
// Created by zhupi on 2024/9/29.
//

#ifndef DEMO2_TREE_BASE_WIDGET_H
#define DEMO2_TREE_BASE_WIDGET_H


//每个节点存储一个结构体，结构体如下：
//    struct TreeStruct{
//    int id_ {0};
//    int parentId_ {0};
//    std::string name_;
//    std::string type_;
//};
// 通过接口void AddTree(TreeStruct tree);添加树，其父节点是结构体中的parentId_，
// 通过void MoveItem(int id);接口来移除节点，参数id对应节点结构体中储存的id_,
// 点击每一个节点，都会发送信号，信号中的内容为本节点的id

#include <QTreeView>
#include <QMenu>
#include <QPainter>
#include <QStyledItemDelegate>
#include <QModelIndex>
#include <QStyleOptionViewItem>
#include <QMouseEvent>
#include "tree_base_common.h"


class TreeItemDelegate : public QStyledItemDelegate {
public:
    TreeItemDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) {}

    void paint(QPainter *painter, const QStyleOptionViewItem &option,
               const QModelIndex &index) const override {
        QStyledItemDelegate::paint(painter, option, index);

        if (!index.isValid()) {
            return;
        }

        painter->save();
        painter->setRenderHint(QPainter::Antialiasing, true);
        painter->setPen(QPen(Qt::lightGray, 1, Qt::SolidLine));

        // 确保 widget 是 QTreeView 类型
        const QTreeView *treeView = qobject_cast<const QTreeView *>(option.widget);
        if (!treeView) {
            painter->restore();
            return;
        }

        QModelIndex parentIndex = index.parent();
        QRect currentRect = option.rect;
        int lineX = currentRect.left() - option.decorationSize.width() / 2; // 线的 X 位置

        // 绘制从父节点到当前节点之间的垂直线
        if (parentIndex.isValid()) {
            QRect parentRect = treeView->visualRect(parentIndex);
            int top = parentRect.bottom();
            int bottom = currentRect.top();
            painter->drawLine(lineX, top, lineX, bottom);
        }

        // 如果有下一个兄弟节点，继续绘制到下一个兄弟节点的竖线
        if (index.row() < index.model()->rowCount(parentIndex) - 1) {
            painter->drawLine(lineX, currentRect.bottom(), lineX, currentRect.bottom() + option.decorationSize.height() / 2);
        }

        painter->restore();
    }
};


class TreeBaseWidget : public QTreeView
{
Q_OBJECT
public:
    explicit TreeBaseWidget(QWidget *parent);
    void AddItem(const TreeStruct &tree);
    void MoveItem(int id);

    // 在 tree_base_widget.cpp 文件中
    void EditItem(const QModelIndex &index)
    {
        if (!index.isValid())
            return;

        // 开始编辑
        edit(index);
    }

signals:
    void DeleteItemSg(int id);

protected:
    // 重写 mouseDoubleClickEvent 方法
    void mouseDoubleClickEvent(QMouseEvent *event) override
    {
        QModelIndex index = indexAt(event->pos());
        if (index.isValid())
            EditItem(index);

        QTreeView::mouseDoubleClickEvent(event);
    }

private:
    // 弹出菜单
    void CustomContextMenu(const QPoint &point);
    // 删除节点
    void DeteteItem(const QModelIndex &index);
};


#endif //DEMO2_TREE_BASE_WIDGET_H
